using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Collections;

/// <summary>
/// Summary description for DataManager
/// </summary>
public class DataManager
{
    string fileName;
    Type type;
    static string baseFilepath = HttpContext.Current.Server.MapPath(@"~/App_Data\\");

    public static string BaseFilePath
    {
        get
        {
            return baseFilepath;
        }
    }

    public DataManager(string fileName, Type type)
    {
        this.fileName = baseFilepath + fileName;
        this.type = type;
    }

    public object LoadData()
    {
        if (File.Exists(this.fileName))
        {
            using (FileStream stream = new FileStream(this.fileName, FileMode.Open))
            {
               XmlSerializer serializer = new XmlSerializer(this.type);
               object data = serializer.Deserialize(stream);
               return data;
            }
        }
        return null;
    }

    public void SaveData(object data)
    {
        try
        {
            if (File.Exists(this.fileName))
            {
                File.Delete(this.fileName);
            }
            using (FileStream stream = new FileStream(this.fileName, FileMode.OpenOrCreate))
            {
                XmlSerializer serializer = new XmlSerializer(this.type);
                serializer.Serialize(stream, data);
            }
        }
        catch(Exception e)
        {
             Logger logger = Logger.GetLogger();
             logger.Write(DateTime.Now.ToString() + ":Save file fail.filename:" +this.fileName + e.Message);
        }
    }
}
